package com.intel.factorytest.activity;

import java.io.IOException;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;

import com.intel.factorytest.R;

public class SpeakerAndHeadsetTest extends BaseActivity implements
        OnClickListener, OnCompletionListener {

    private TextView mTextView = null;

    private int count = 0;
    private final String TAG = "SpeakerAndHeadsetTest";
    // private Button mMediaVolumeUp = null;
    // private Button mMediaVolumeDown = null;
    // private Button mRingVolumeUp = null;
    // private Button mRingVolumeDown = null;
    // private Button mAlarmVolumeUp = null;
    // private Button mAlarmVolumeDown = null;
    private AudioManager mAudioManager = null;
    // private Ringtone mMediaRingtone = null;
    // private Ringtone mRingRingtone = null;
    // private Ringtone mAlarmRingtone = null;
    // private SeekBar mMediaSeekBar = null;
    // private SeekBar mRingSeekBar = null;
    // private SeekBar mAlarmSeekBar = null;
    private TextView mHeadsetStatusTXT = null;
    private MediaPlayer mMusicPalyer = null;
    // private ImageView mHeadsetStatusImgView = null;
    // private RadioButton mHeadsetRadioBtn = null;

    private Button mSuessbtn;
    private Button mFailebtn;

    private boolean headsetConnected = false;
    private BroadcastReceiver headsetReceiver = null;

    private static int save_volume_music = 0;

    public void onCreate(Bundle b) {

        super.onCreate(b);
        // mTextView = new TextView(this);
        // mTextView.setTextSize(25.0f);
        // mTextView.setGravity(Gravity.CENTER);
        setContentView(R.layout.volume);
        // mMediaVolumeUp = (Button) findViewById(R.id.media_volume_up);
        // mMediaVolumeUp.setOnClickListener(this);
        // mMediaVolumeDown = (Button) findViewById(R.id.media_volume_down);
        // mMediaVolumeDown.setOnClickListener(this);
        // mRingVolumeUp = (Button) findViewById(R.id.ring_volume_up);
        // mRingVolumeUp.setOnClickListener(this);
        // mRingVolumeDown = (Button) findViewById(R.id.ring_volume_down);
        // mRingVolumeDown.setOnClickListener(this);
        // mAlarmVolumeUp = (Button) findViewById(R.id.alarm_volume_up);
        // mAlarmVolumeUp.setOnClickListener(this);
        // mAlarmVolumeDown = (Button) findViewById(R.id.alarm_volume_down);
        // mAlarmVolumeDown.setOnClickListener(this);
        mSuessbtn = (Button) findViewById(R.id.success_button);
        mFailebtn = (Button) findViewById(R.id.fail_button);
        mSuessbtn.setVisibility(View.INVISIBLE);

        mSuessbtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                is_pass = true;
                finish();
            }
        });
        attachOnTouchListener(mSuessbtn);

        mFailebtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                is_pass = false;
                finish();
            }
        });
        attachOnTouchListener(mFailebtn);

        Uri tempUri = getDefaultRingtoneUri(RingtoneManager.TYPE_RINGTONE);
        if (tempUri != null) {
            mMusicPalyer = MediaPlayer.create(this, tempUri);
        } else {
            mMusicPalyer = MediaPlayer.create(this, R.raw.test_music);
        }

        // mMusicPalyer = MediaPlayer.create(this, R.raw.test);
        mMusicPalyer.stop();
        mMusicPalyer.setAudioStreamType(AudioManager.STREAM_MUSIC);

        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        mHeadsetStatusTXT = (TextView) findViewById(R.id.headset_status);
        mAudioManager.setMode(AudioManager.MODE_NORMAL);
        mAudioManager.setSpeakerphoneOn(true);

        save_volume_music = mAudioManager
                .getStreamVolume(AudioManager.STREAM_MUSIC);
        int maxVolume = mAudioManager
                .getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                (int) (maxVolume), AudioManager.FLAG_PLAY_SOUND);

        // startPlayback();
        try {
            mMusicPalyer.prepare();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        mMusicPalyer.start();
        mMusicPalyer.setLooping(true);
        // mMusicPalyer.setOnCompletionListener(this);

        updateHeadsetStatus();
        headsetReceiver = new HeadsetStatusChangedReceiver();
        Log.i(TAG, "oncreate");
    }

    private void ResetPlay() {
        if (mMusicPalyer.isPlaying()) {
            mMusicPalyer.reset();
        }

        try {
            mMusicPalyer.prepare();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        mMusicPalyer.start();
        mMusicPalyer.setLooping(true);
    }

    private void updateHeadsetStatus() {
        headsetConnected = mAudioManager.isWiredHeadsetOn();
        // mAudioManager.setStreamVolume(AudioManager.STREAM_RING,
        // mRingSeekBar.getProgress(), 0);
        if (headsetConnected) {
            mSuessbtn.setVisibility(View.VISIBLE);
            mHeadsetStatusTXT.setText(R.string.SERVICEMENU_HEADSET_PLUG_TXT);
            mHeadsetStatusTXT.setCompoundDrawablesWithIntrinsicBounds(null,
                    null, getResources().getDrawable(R.drawable.btn_check_on),
                    null);
            // mHeadsetStatusImgView.setBackgroundResource(R.drawable.btn_check_on);
            // mHeadsetRadioBtn.setText(R.string.SERVICEMENU_HEADSET_PLUG_TXT);
            // mHeadsetRadioBtn.setChecked(true);
            // close speaker
            // mAudioManager.setMode(AudioManager.ROUTE_SPEAKER);
            // if(mAudioManager.isSpeakerphoneOn()) {
            // mAudioManager.setSpeakerphoneOn(false);
            // // mAudioManager.setStreamVolume(AudioManager.STREAM_RING,
            // mRingSeekBar.getProgress(), 0);
            // }

        } else {
            mHeadsetStatusTXT.setText(R.string.SERVICEMENU_HEADSET_UNPLUG_TXT);
            mHeadsetStatusTXT.setCompoundDrawablesWithIntrinsicBounds(null,
                    null, getResources().getDrawable(R.drawable.btn_check_off),
                    null);
            // mHeadsetStatusImgView.setBackgroundResource(R.drawable.btn_check_off);
            // mHeadsetRadioBtn.setText(R.string.SERVICEMENU_HEADSET_UNPLUG_TXT);
            // mHeadsetRadioBtn.setChecked(false);
            // open speaker
            // mAudioManager.setMode(AudioManager.ROUTE_HEADSET);
            // if(!mAudioManager.isSpeakerphoneOn()) {
            // mAudioManager.setSpeakerphoneOn(true);
            // // mAudioManager.setStreamVolume(AudioManager.STREAM_RING,
            // mRingSeekBar.getProgress(), 0);
            // }

        }
    }

    private void startPlayback() {
        // set to 90% * maxvolumeWW
        // int maxVolume =
        // mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        // mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, (int)
        // (maxVolume), 0);
        // mMediaSeekBar.setProgress(mMediaSeekBar.getMax() / 2);
        // mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
        // mMediaSeekBar.getProgress(), 0);

        // init mediaplay
        Uri tempUri = getDefaultRingtoneUri(RingtoneManager.TYPE_NOTIFICATION);
        if (tempUri == null) {
            mMusicPalyer = MediaPlayer.create(SpeakerAndHeadsetTest.this,
                    R.raw.test_music);
            mMusicPalyer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mMusicPalyer.setLooping(true);
            try {
                mMusicPalyer.prepare();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            mMusicPalyer.start();
        } else {
            mMusicPalyer = new MediaPlayer();
            try {
                mMusicPalyer.setDataSource(this, tempUri);
                mMusicPalyer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mMusicPalyer.setLooping(true);
                mMusicPalyer.prepare();
                mMusicPalyer.start();
            } catch (IOException e) {
                // TODO: handle exception
            }
        }

        // if(!isMediaPlaying())mMediaRingtone.play();
    }

    private void stopPlayback() {
        if (mMusicPalyer != null) {
            if (mMusicPalyer.isPlaying()) {
                mMusicPalyer.reset();
                mMusicPalyer.release();
                mMusicPalyer = null;
            }
        }
    }

    // public boolean isMediaPlaying() {
    // return mMediaRingtone != null && mMediaRingtone.isPlaying();
    // }
    //
    // public boolean isRingPlaying() {
    // return mRingRingtone != null && mRingRingtone.isPlaying();
    // }
    //
    // public boolean isAlarmPlaying() {
    // return mAlarmRingtone != null && mAlarmRingtone.isPlaying();
    // }
    //
    // private Uri getMediaVolumeUri(Context context) {
    // // return Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
    // // + context.getPackageName() + "/" + R.raw.media_volume);
    // return getDefaultRingtoneUri(RingtoneManager.TYPE_RINGTONE);
    // }

    public Uri getDefaultRingtoneUri(int type) {
        return RingtoneManager.getActualDefaultRingtoneUri(this, type);
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        IntentFilter filter = new IntentFilter(headsetAction);
        this.registerReceiver(headsetReceiver, filter, "permission.CIT_ALLOW_BROADCAST", null);
        super.onStart();
    }

    public void onResume() {
        Log.d(TAG, "onResume");
        super.onResume();
        // try {
        // mMusicPalyer.prepare();
        // } catch (IllegalStateException e) {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // } catch (IOException e) {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }
        // mMusicPalyer.start();
    }

    public void onPause() {
        Log.d(TAG, "onPause");
        super.onPause();
    }

    public void onClick(View v) {

    }

    // public void onClick(View v) {
    // if (v.getId() == R.id.media_volume_up) {
    // //mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
    // AudioManager.ADJUST_RAISE, AudioManager.FX_FOCUS_NAVIGATION_UP);
    // if(mMediaSeekBar.getProgress() < mMediaSeekBar.getMax()) {
    // mMediaSeekBar.setProgress(mMediaSeekBar.getProgress() + 1);
    // }
    // mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
    // mMediaSeekBar.getProgress(), 0);
    //
    // if(isRingPlaying())mRingRingtone.stop();
    // if(isAlarmPlaying())mAlarmRingtone.stop();
    // if(!isMediaPlaying())mMediaRingtone.play();
    //
    // } else if (v.getId() == R.id.media_volume_down) {
    // //mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
    // AudioManager.ADJUST_LOWER, AudioManager.FX_FOCUS_NAVIGATION_UP);
    // if(mMediaSeekBar.getProgress() > 0) {
    // mMediaSeekBar.setProgress(mMediaSeekBar.getProgress() - 1);
    // }
    // mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
    // mMediaSeekBar.getProgress(), 0);
    // if(isRingPlaying())mRingRingtone.stop();
    // if(isAlarmPlaying())mAlarmRingtone.stop();
    // if(!isMediaPlaying())mMediaRingtone.play();
    //
    // } else if (v.getId() == R.id.ring_volume_up) {
    // //mAudioManager.adjustStreamVolume(AudioManager.STREAM_RING,
    // AudioManager.ADJUST_RAISE, AudioManager.FX_FOCUS_NAVIGATION_UP);
    // if(mRingSeekBar.getProgress() < mRingSeekBar.getMax()) {
    // mRingSeekBar.setProgress(mRingSeekBar.getProgress() + 1);
    // }
    // mAudioManager.setStreamVolume(AudioManager.STREAM_RING,
    // mRingSeekBar.getProgress(), 0);
    // if(isAlarmPlaying())mAlarmRingtone.stop();
    // if(isMediaPlaying())mMediaRingtone.stop();
    // if(!isRingPlaying())mRingRingtone.play();
    //
    // } else if (v.getId() == R.id.ring_volume_down) {
    // if(mRingSeekBar.getProgress() > 0) {
    // mRingSeekBar.setProgress(mRingSeekBar.getProgress() - 1);
    // }
    // mAudioManager.setStreamVolume(AudioManager.STREAM_RING,
    // mRingSeekBar.getProgress(), 0);
    // //mAudioManager.adjustStreamVolume(AudioManager.STREAM_RING,
    // AudioManager.ADJUST_LOWER, AudioManager.FX_FOCUS_NAVIGATION_UP);
    // if(isAlarmPlaying())mAlarmRingtone.stop();
    // if(isMediaPlaying())mMediaRingtone.stop();
    // if(!isRingPlaying())mRingRingtone.play();
    //
    // } else if (v.getId() == R.id.alarm_volume_up) {
    // //mAudioManager.adjustStreamVolume(AudioManager.STREAM_ALARM,
    // AudioManager.ADJUST_RAISE, AudioManager.FX_FOCUS_NAVIGATION_UP);
    // if(mAlarmSeekBar.getProgress() < mAlarmSeekBar.getMax()) {
    // mAlarmSeekBar.setProgress(mAlarmSeekBar.getProgress() + 1);
    // }
    // mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM,
    // mAlarmSeekBar.getProgress(), 0);
    // if(isMediaPlaying())mMediaRingtone.stop();
    // if(isRingPlaying())mRingRingtone.stop();
    // if(!isAlarmPlaying())mAlarmRingtone.play();
    //
    // } else if (v.getId() == R.id.alarm_volume_down) {
    // //mAudioManager.adjustStreamVolume(AudioManager.STREAM_ALARM,
    // AudioManager.ADJUST_LOWER, AudioManager.FX_FOCUS_NAVIGATION_UP);
    // if(mAlarmSeekBar.getProgress() > 0) {
    // mAlarmSeekBar.setProgress(mAlarmSeekBar.getProgress() - 1);
    // }
    // mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM,
    // mAlarmSeekBar.getProgress(), 0);
    // if(isMediaPlaying())mMediaRingtone.stop();
    // if(isRingPlaying())mRingRingtone.stop();
    // if(!isAlarmPlaying())mAlarmRingtone.play();
    //
    // }
    //
    // }
    @Override
    protected void onDestroy() {
        Log.d(TAG, "onDestroy");
        // if(isMediaPlaying())mMediaRingtone.stop();
        // if(isRingPlaying())mRingRingtone.stop();
        // if(isAlarmPlaying())mAlarmRingtone.stop();
        stopPlayback();
        recoverMode();
        mMusicPalyer = null;
        super.onDestroy();
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        unregisterReceiver(headsetReceiver);
        super.onStop();
    }

    @Override
    public void finish() {
        tc.setTestResult(is_pass);
        super.finish();
    }

    private void recoverMode() {
        Log.d(TAG, "recoverMode");
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                save_volume_music, AudioManager.FLAG_PLAY_SOUND);
    }

    private String headsetAction = "android.intent.action.HEADSET_PLUG";

    class HeadsetStatusChangedReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String action = intent.getAction();
            if (action.equals(headsetAction)) {
                updateHeadsetStatus();
                // Log.e(TAG,
                // "mMusicPalyer.isLooping()"+mMusicPalyer.isLooping());
                // ResetPlay();
            }
        }
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        // TODO Auto-generated method stub

        Log.d(TAG, "onCompletion");

    }
}
